﻿using CqCore.Commands;
using SuperShopInfrastructure.Models.Consignee;
using SuperShopInfrastructure.Static;
using SuperShopRepository;
using SuperShopService.IServices;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace SuperShopService.Services
{
    public class ConsigneeService : IConsigneeService
    {
        private readonly ConsigneeRepository consigneeRepository;

        public ConsigneeService(ConsigneeRepository consigneeRepository)
        {
            this.consigneeRepository = consigneeRepository;
        }

        public async Task<CommandResult<bool>> Add(CreateOrEditConsigneeCommand command)
        {
            var ret = await consigneeRepository.Add(command);
            switch (ret)
            {
                case 1:
                    return CommandResult<bool>.Success(true);
                case 2:
                    return CommandResult<bool>.Failure("用户异常");
                default:
                    return CommandResult<bool>.Failure("请求出错");

            }
        }

        public async Task Del(int id, int userid)
        {
            await consigneeRepository.Del(id, userid);
        }

        public async Task Edit(CreateOrEditConsigneeCommand command)
        {
            await consigneeRepository.Edit(command);
        }

        public async Task<List<ConsigneeViewModel>> GetList(int userid)
        {
            var res = new List<ConsigneeViewModel>();
            var ds = await consigneeRepository.GetList(userid);
            if (DataManager.CheckDs(ds, 1) && DataManager.CheckHasRow(ds.Tables[0]))
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    res.Add(new ConsigneeViewModel()
                    {
                        Id = Convert.ToInt32(dr["Id"]),
                        IsDefault = Convert.ToInt32(dr["IsDefault"]),
                        ConsigneeName = dr["ConsigneeName"].ToString(),
                        ConsigneePhone = dr["ConsigneePhone"].ToString(),
                        ZipCode = dr["ZipCode"].ToString(),
                        ProvinceName = dr["ProvinceName"].ToString(),
                        CityName = dr["CityName"].ToString(),
                        AreaName = dr["AreaName"].ToString(),
                        ProvinceCode = dr["ProvinceCode"].ToString(),
                        CityCode = dr["CityCode"].ToString(),
                        AreaCode = dr["AreaCode"].ToString(),
                        Address = dr["Address"].ToString()
                    });
                }
            }
            return res;
        }

        public async Task UpdateIsDefault(int id, int userid, int isdefault)
        {
            await consigneeRepository.UpdateIsDefault(id, userid, isdefault);
        }
    }
}
